<!--
  * 陈列模版表单
  *
-->
<template>
  <a-drawer :title="formTitle" :open="visible" @close="onClose">
    <template #closeIcon>
      <div class="express-bar"></div>
      <div class="express-btn">
        <CloseCircleOutlined :size="32" @click="onClose" />
      </div>
    </template>
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ sm: 4, lg: 6 }">
      <!---------- 基本信息 begin ----------->
      <a-card title="基本信息" class="smart-margin-bottom10">
        <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="协议名称" name="template_name">
              <a-input v-model:value="form.template_name" placeholder="请输入协议名称" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="陈列周期" name="display_cycle">
              <EnumSelect enum-name="DISPLAY_STATUS_ENUM" v-model:value="form.display_cycle" placeholder="陈列周期" @change="updateColumns" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
      <!---------- 基本信息 end ----------->
      <!---------- 商品信息 begin ----------->
      <a-card title="商品信息" class="smart-margin-bottom10">
        <template #extra>
          <a-button @click="addFormCash()" type="primary" v-privilege="'goods:add'" style="margin-right: 10px">
            <template #icon>
              <PlusOutlined />
            </template>
            增加现金
          </a-button>
          <a-button @click="showGoodsSelectModal()" type="primary" v-privilege="'goods:add'">
            <template #icon>
              <PlusOutlined />
            </template>
            增加商品
          </a-button>
        </template>
        <a-table size="small" :dataSource="form.detail" :columns="columns" :scroll="{ x: 'max-content' }" :pagination="false" :showSorterTooltip="false" bordered>
          <template #bodyCell="{ text, record, column, index }">
            <template v-if="column.dataIndex === 'purchase_total_price'"> {{ text }}</template>
            <template v-if="column.dataIndex.startsWith('第')">
              <a-form-item
                class="form-table-item"
                v-if="record.type == 1"
                required
                :name="['detail', index, `${column.dataIndex}`]"
                :rules="[
                  {
                    required: true,
                    message: '请输入金额'
                  }
                ]"
              >
                <a-input-number v-model:value="record[column.dataIndex]" :min="1" :precision="2" placeholder="请输入金额" @change="calculateTotal(record)" />
              </a-form-item>
              <a-form-item
                class="form-table-item"
                v-else
                required
                :name="['detail', index, `${column.dataIndex}`]"
                :rules="[
                  {
                    required: true,
                    message: '请输入数量'
                  }
                ]"
              >
                <a-input-number v-model:value="record[column.dataIndex]" :min="1" :precision="0" placeholder="请输入数量" @change="calculateTotal(record)" />
              </a-form-item>
            </template>
            <template v-if="column.dataIndex === 'action'">
              <div class="smart-table-operate">
                <a-button @click="delFormDetail(index)" danger type="link" v-privilege="'goods:delete'">删除</a-button>
              </div>
            </template>
          </template>
        </a-table>
      </a-card>
      <!---------- 商品信息 end ----------->
      <!---------- 信息 begin ----------->
      <a-card title="" class="smart-margin-bottom10">
        <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
          <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
            <a-form-item label="陈列要求" name="display_requirements">
              <a-input v-model:value="form.display_requirements" placeholder="请输入陈列要求" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
    </a-form>
    <GoodsSelectModal ref="goodsSelectModalRef" @confirm="onSelectGoods" />
    <template #footer>
      <div class="smart-table-operate-block">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </div>
    </template>
  </a-drawer>
</template>
<script setup lang="ts">
import { message } from 'ant-design-vue'
import _ from 'lodash'
import { errorSentry } from '@/lib/error-sentry'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import GoodsSelectModal from './goods-select-modal.vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import { displayApi } from '@/api/business/marketing/display-api'
const loadingStore = useLoadingStore()
// emit
const emit = defineEmits(['reloadList'])

// 组件ref
const formRef = ref()

const formDefault = {
  // 协议名称
  template_name: '',
  // 陈列周期
  display_cycle: undefined,
  // 陈列要求
  display_requirements: '',
  // 商品数据
  detail: []
}
const form = ref({ ...formDefault })

const rules = ref({
  template_name: [{ required: true, message: '请输入协议名称' }],
  display_cycle: [{ required: true, message: '请选择陈列周期' }]
})

// 是否展示抽屉
const visible = ref(false)

function showDrawer(rowData) {
  form.value = _.cloneDeep(formDefault)
  if (rowData.id && !_.isEmpty(rowData)) {
    form.value = _.pick(rowData, ['id', ...Object.keys(formDefault)])
    if (form.value.id) {
      // 加载商品详情数据
      form.value.detail = rowData.detail.map((item) => {
        const rewardSet = item.reward_set || []
        const months = {}
        rewardSet.forEach((monthData) => {
          // const monthKey = Object.keys(monthData)[0]
          months[monthData.cycle_date] = monthData.cycle_num
        })
        return {
          ...item,
          ...months,
          reward_set: rewardSet // 保留原始 reward_set 数据
        }
      })
      // 计算每条记录的总计
      form.value.detail.forEach((item) => {
        calculateTotal(item)
      })
    }
    updateColumns()
  }

  visible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

function onClose() {
  form.value = formDefault
  deletedGoods.value = []
  visible.value = false
}

async function onSubmit() {
  // 去除空行
  unref(form).detail = _.filter(unref(form).detail, (item) => {
    return !_.every(item, (value) => value === null)
  })
  await nextTick()
  formRef.value
    .validate()
    .then(async () => {
      loadingStore.show()
      try {
        if (unref(form).id) {
          function processRewardSet(detailData) {
            const monthCount = parseInt(form.value.display_cycle, 10)

            // 遍历每条数据
            detailData.forEach((item) => {
              const rewardSet = []
              for (let i = 1; i <= monthCount; i++) {
                const monthKey = `第${i}月`
                if (item[monthKey]) {
                  // rewardSet.push({ [monthKey]: item[monthKey] })
                  rewardSet.push({ cycle_date: monthKey, cycle_num: item[monthKey] })
                }
              }
              item.reward_set = rewardSet // 添加 reward_set 属性
            })

            return detailData
          }

          // 调用处理函数
          const processedData = processRewardSet(unref(form).detail)
          const keys = ['goods_no', 'name', 'goods_id', 'bar_code', 'spec', 'unit', 'spec_id', 'type', 'reward_set']
          const specData = _(processedData)
            .cloneDeep()
            .map((item) => _.pick(item, keys))
          const data = {
            ...unref(form),
            detail: JSON.stringify(specData)
          }
          await displayApi.templateEdit(data)
        } else {
          function processRewardSet(detailData) {
            const monthCount = parseInt(form.value.display_cycle, 10)

            // 遍历每条数据
            detailData.forEach((item) => {
              const rewardSet = []
              for (let i = 1; i <= monthCount; i++) {
                const monthKey = `第${i}月`
                if (item[monthKey]) {
                  // rewardSet.push({ [monthKey]: item[monthKey] })
                  rewardSet.push({ cycle_date: monthKey, cycle_num: item[monthKey] })
                }
              }
              item.reward_set = rewardSet // 添加 reward_set 属性
            })

            return detailData
          }

          // 调用处理函数
          const processedData = processRewardSet(unref(form).detail)
          const keys = ['goods_no', 'name', 'goods_id', 'bar_code', 'spec', 'unit', 'spec_id', 'type', 'reward_set']
          const specData = _(processedData)
            .cloneDeep()
            .map((item) => _.pick(item, keys))
          const data = {
            ...unref(form),
            detail: JSON.stringify(specData)
          }
          await displayApi.templateAdd(data)
        }
        message.success('操作成功')
        onClose()
        emit('reloadList')
      } catch (error) {
        message.error(error.msg)
        errorSentry.captureError(error)
      } finally {
        loadingStore.hide()
      }
    })
    .catch((error) => {
      console.log('error', error)
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}

defineExpose({
  showDrawer
})

// 商品选择弹窗
const goodsSelectModalRef = ref()
// 记录点击多选按钮的表格行索引，插入数据时使用
function showGoodsSelectModal() {
  goodsSelectModalRef.value.showModal()
}

// 记录已删除的商品
const deletedGoods = ref([])

// 商品选择回调
function onSelectGoods(goodsList) {
  // 处理商品数据
  function handleGoodsData(rowData) {
    const keys = ['goods_name', 'img', 'no', 'unit', 'spec']
    const specData = _.find(rowData.spec, (item) => item.unit_type === rowData.default_unit_type)
    return {
      ..._.pick(rowData, keys),
      goods_no: rowData.no,
      name: rowData.goods_name,
      bar_code: specData.barcode,
      spec_id: specData.id,
      spec: specData.spec_name,
      unit: specData.unit_name,
      goods_id: specData.goods_id,
      type: 2
    }
  }

  // 遍历处理后的商品数据
  const rows = _.map(goodsList, handleGoodsData)
  rows.forEach((row) => {
    // 检查form.value.detail中是否已存在相同spec_id和goods_id的项
    const existingItem = form.value.detail.find((item) => item.spec_id === row.spec_id && item.goods_id === row.goods_id)
    if (!existingItem) {
      // 如果不存在，则添加到form.value.detail中
      form.value.detail.push(row)
    } else {
      message.error(`该规格商品${row.name}已存在，不再重复添加。`)
    }
  })
}

// ----------------------------------  商品信息  ----------------------------------
// 表头配置
const columns = ref([
  {
    title: '商品编号',
    dataIndex: 'goods_no'
  },
  {
    title: '商品/现金',
    dataIndex: 'name'
  },
  {
    title: '规格属性',
    dataIndex: 'spec'
  },
  {
    title: '单位',
    dataIndex: 'unit'
  },
  {
    title: '条码',
    dataIndex: 'bar_code'
  },
  {
    title: '总计',
    dataIndex: 'purchase_total_price',
    width: 150
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right'
  }
])
// 新增月份
function updateColumns() {
  const monthCount = parseInt(form.value.display_cycle, 10)
  if (isNaN(monthCount) || monthCount <= 0) {
    message.error('陈列周期格式不正确')
    return
  }

  // 清空旧的月份列
  columns.value = columns.value.filter((col) => !col.dataIndex.startsWith('第'))

  // 添加新的月份列
  const newColumns = Array.from({ length: monthCount }, (_, index) => ({
    title: `第${index + 1}月`,
    dataIndex: `第${index + 1}月`,
    width: 150
  }))

  // 插入月份列到“总计”列之前
  const totalIndex = columns.value.findIndex((col) => col.dataIndex === 'purchase_total_price')
  columns.value.splice(totalIndex, 0, ...newColumns)
}

// 增加现金
function addFormCash() {
  form.value.detail.push({ type: 1, goods_no: '', name: '现金', spec: '', unit: '元', bar_code: '' })
}
// 总计
function calculateTotal(record) {
  let total = 0
  const monthCount = parseInt(form.value.display_cycle, 10)
  for (let i = 1; i <= monthCount; i++) {
    const monthKey = `第${i}月`
    if (record[monthKey]) {
      total += record[monthKey]
    }
  }
  record.purchase_total_price = total
}

// 删除行
function delFormDetail(index: number) {
  const formDetail = unref(form).detail // 获取当前的详情数组
  // 删除指定索引的元素
  formDetail.splice(index, 1)
}

// 表单标题
const formTitle = computed(() => (form.value.id ? '编辑' : '新建'))
</script>
<style scoped lang="less">
.form-table-item {
  margin-bottom: 0;
  max-width: 200px;
}
.form-table-index {
  width: 100%;
  height: 100%;
  overflow: hidden;
  text-align: center;
  .form-table-index-btn-wrap {
    display: none;
  }
  .form-table-index-btn {
    display: flex;
  }
  .form-table-index-btn-item {
    width: 50%;
    height: 100%;
    font-size: 14px;
    font-weight: bold;
    text-align: center;
    cursor: pointer;
    user-select: none;
  }
  .form-table-index-btn-item:hover {
    background: #f87171ff;
    color: white;
  }
}
.form-table-index:hover span {
  display: none;
}
.form-table-index:hover .form-table-index-btn-wrap {
  display: block;
}
</style>
